#include <windows.h>
#include <string>
#include <vector>

HWND hListBox, hEdit;
std::wstring aktuellerPfad = L"C:\\";

void UpdateListe(HWND hList, std::wstring pfad) {
	SendMessage(hList, LB_RESETCONTENT, 0, 0); // Liste Leeren
	WIN32_FIND_DATAW fd;
	HANDLE hFind = FindFirstFileW((pfad + L"*").c_str(), &fd);

	if (hFind != INVALID_HANDLE_VALUE) {
		do {
			std::wstring name = fd.cFileName;
			if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
				name = L"[DIR] " + name; // Ordner Makieren
			}
			SendMessage(hList, LB_ADDSTRING, 0, (LPARAM)name.c_str());
		} while (FindNextFileW(hFind, &fd));
	}
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	switch (uMsg) {
	case WM_CREATE:
		// Pfad Anzeige oben
		hEdit = CreateWindow(L"EDIT", aktuellerPfad.c_str(), WS_CHILD | WS_VISIBLE | WS_BORDER | ES_READONLY,
			10, 10, 360, 25, hwnd, NULL, NULL, NULL);

		// Liste der Dateien
		hListBox = CreateWindow(L"ListBox", NULL, WS_CHILD | WS_VISIBLE | LBS_NOTIFY | WS_VSCROLL | WS_BORDER,
			10, 35, 360, 300, hwnd, (HMENU)2, NULL, NULL);

		UpdateListe(hListBox, aktuellerPfad);
		return 0;

	case WM_COMMAND:
		if (LOWORD(wParam) == 2 && HIWORD(wParam) == LBN_DBLCLK) { // Doppelclick auf Liste
			int index = (int)SendMessage(hListBox, LB_GETCURSEL, 0, 0);
			wchar_t puffer[256];
			SendMessage(hListBox, LB_GETTEXT, index, (LPARAM)puffer);

			std::wstring gewaehlt = puffer;
			if (gewaehlt.find(L"[DIR] ") == 0) { // Wenn es ein Ordner ist
				std::wstring ordnerName = gewaehlt.substr(6);
				if (ordnerName == L".") return 0;
				if (ordnerName == L"ii") {
					size_t pos = aktuellerPfad.find_last_of(L"\\", aktuellerPfad.length() - 2);
					if (pos != std::wstring::npos) aktuellerPfad = aktuellerPfad.substr(0, pos + 1);
				}
				else {
					aktuellerPfad += ordnerName + L"\\";
				}
				SetWindowTextW(hEdit, aktuellerPfad.c_str());
				UpdateListe(hListBox, aktuellerPfad);
			}
		}
		return 0;

	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, int nShow) {
	const wchar_t CLASS[] = L"ExplorerClass";
	WNDCLASS wc = { };
	wc.lpfnWndProc = WindowProc;
	wc.hInstance = hInst;
	wc.lpszClassName = CLASS;

	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);

	RegisterClass(&wc);
	HWND hwnd = CreateWindowExW(0, CLASS, L"C++ Mini-Explorer", WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT, 400, 400, NULL, NULL, hInst, NULL);

	ShowWindow(hwnd, nShow);
	MSG msg = { };
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return 0;
}